/**
 * [18] 四数之和
 *
 * @format
 * @lc app=leetcode.cn id=18 lang=javascript
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[][]}
 */
var fourSum = function (nums, target) {
    const result = []
    if (nums.length < 4) return result
    nums.sort((a, b) => a - b)
    for (let i = 0; i < nums.length - 3; i++) {
        if (i > 0 && nums[i] == nums[i - 1]) continue
        for (let j = i + 1; j < nums.length - 2; j++) {
            if (j > i + 1 && nums[j] == nums[j - 1]) continue
            let [left, right] = [j + 1, nums.length - 1]
            const SUM_BEFORE = nums[i] + nums[j]
            while (left < right) {
                const SUM = SUM_BEFORE + nums[left] + nums[right]
                if (SUM == target) {
                    result.push([nums[i], nums[j], nums[left], nums[right]])
                    while (left < right && nums[left] == nums[left + 1]) left++
                    while (left < right && nums[right] == nums[right - 1])
                        right--
                    left++
                    right--
                } else if (SUM < target) left++
                else right--
            }
        }
    }
    return result
}
debugger
nums = [-2, -1, -1, 1, 1, 2, 2]
target = 0
console.log(fourSum(nums, target))
// @lc code=end
